package com.yocard.yxyd.adapter;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.SparseArrayCompat;
import android.view.ViewGroup;
import android.webkit.ValueCallback;

import com.yocard.yxyd.base.AppContext;
import com.yocard.yxyd.ui.fragment.CsmDetailFragment;
import com.yocard.yxyd.ui.fragment.CsmReundListFragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2019/4/2.
 * 订单详情 19/05/05
 */
public class CsmDetailFragmentAdapter extends FragmentPagerAdapter {

    private String csmId;
    private final ValueCallback<Integer> callback;
    private List<String> titles;
    private SparseArrayCompat<WeakReference<Fragment>> holder;
    protected List<Class> fragments;

    public CsmDetailFragmentAdapter(FragmentManager fm, String csmId,ValueCallback<Integer> callback) {
        super(fm);
        this.csmId = csmId;
        this.callback = callback;
        titles = new ArrayList<>();
        titles.add("订单详情");
        titles.add("跟进记录");

        fragments = new ArrayList<>();
        fragments.add(CsmDetailFragment.class);
        fragments.add(CsmReundListFragment.class);

        this.holder = new SparseArrayCompat<>(titles.size());
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        Object item = super.instantiateItem(container, position);
        if (item instanceof Fragment) {
            holder.put(position, new WeakReference<Fragment>((Fragment) item));
        }
        return item;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        holder.remove(position);
        super.destroyItem(container, position, object);
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = Fragment.instantiate(AppContext.getContext(), fragments.get(i).getName());
        Bundle bundle = new Bundle();
        bundle.putString("csmId",csmId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int getCount() {
        return titles.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }
}
